package com.qys.livesMall.shop.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.mongodb.client.result.DeleteResult;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.shop.dao.H2ShopBaseDao;
import com.qys.livesMall.shop.mapper.ShopCartMapper;
import com.qys.livesMall.shop.modal.dto.ShopCartDto;
import com.qys.livesMall.shop.modal.entity.*;
import com.qys.livesMall.shop.service.ShopCartService;
import com.qys.livesMall.shop.service.ShopGoodsInfoService;
import com.qys.livesMall.shop.service.ShopGoodsSkuService;
import com.qys.livesMall.shop.service.ShopGoodsSkuStocksService;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;

/**
 * @packageName:
 * @className:ShopCartServiceImpl
 * @Description:
 * @author:guomx
 * @date:2023/6/199:57
 */
@Service
public class ShopCartServiceImpl implements ShopCartService {
    @Resource
    private ShopCartMapper cartMapper;
    @Resource
    private H2ShopBaseDao h2ShopBaseDao;
    @Resource
    private ShopGoodsInfoService infoService;
    @Resource
    private ShopGoodsSkuService skuService;

    @Resource
    private ShopGoodsSkuStocksService stocksService;

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public R add(ShopCartDto cartDto, Long userId, String userName) {
        cartMapper.deleteById(userName+cartDto.getSkuId());
        if(cartDto.getNum()>0){
//查询Sku
            ShopGoodsSku sku = skuService.getById(cartDto.getSkuId());

            Long skuId = sku.getId();
            LambdaQueryWrapper<ShopGoodsSkuStocks> stocksWrapper = new LambdaQueryWrapper<>();
            stocksWrapper.eq(ShopGoodsSkuStocks::getSkuId,skuId);
            stocksWrapper.eq(ShopGoodsSkuStocks::getState,false);
            stocksWrapper.ne(ShopGoodsSkuStocks::getNum,0);
            stocksWrapper.orderByAsc(ShopGoodsSkuStocks::getCreateTime);
            List<ShopGoodsSkuStocks> stocks = stocksService.list(stocksWrapper);
            if (ObjectUtils.isEmpty(stocks)) {
                return R.fail(MessageUtils.message("understock"));
            }
            int totalNum = stocks.stream().mapToInt(ShopGoodsSkuStocks::getNum).sum();
            ShopGoodsSkuStocks minStocks = stocks.stream().min(Comparator.comparing(ShopGoodsSkuStocks::getCreateTime)).orElse(null);
            Integer stocksNum = minStocks.getNum();
            if(cartDto.getNum()>stocksNum)return R.fail(stocksNum,sku.getGoodsName()+MessageUtils.message("understock"));
            BigDecimal price = minStocks.getPrice();
            sku.setTotalNum(totalNum);
            sku.setAvailableNum(stocksNum);
            sku.setPrice(price);
            sku.setOriginalPrice(price);

//将Sku转换成Cart
            ShopCart cart = new ShopCart();
            if (ObjectUtils.isNotEmpty(cartDto.getAnchorId())){
                cart.setAnchorId(cartDto.getAnchorId());
            }
            cart.setUserId(userId);
            cart.setUserName(userName);
            cart.setSkuId(cartDto.getSkuId());
            cart.setNum(cartDto.getNum());
            cart.setAnchorId(cartDto.getAnchorId());
            cart.setTaskId(cartDto.getTaskId());
            sku2cart(sku,cart);
//批量增加
            cartMapper.save(cart);
        }
      return R.ok();
    }

    @Override
    public List<ShopCart> list(Long userId) {
        ShopCart shopCart = new ShopCart();
        shopCart.setUserId(userId);
        List<ShopCart> list= cartMapper.findAll(Example.of(shopCart), Sort.by("_id"));
        for (ShopCart bean : list) {
            LambdaQueryWrapper<ShopGoodsSkuStocks> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ShopGoodsSkuStocks::getSkuId,bean.getSkuId());
            lambdaQueryWrapper.eq(ShopGoodsSkuStocks::getState,false);
            lambdaQueryWrapper.ne(ShopGoodsSkuStocks::getNum,0);
            lambdaQueryWrapper.orderByAsc(ShopGoodsSkuStocks::getCreateTime);
            List<ShopGoodsSkuStocks> shopGoodsSkuStocks= stocksService.list(lambdaQueryWrapper);
            Integer inventoryNum=null;
            if (CollectionUtil.isNotEmpty(shopGoodsSkuStocks)){
                inventoryNum = shopGoodsSkuStocks.stream().mapToInt(ShopGoodsSkuStocks::getNum).sum();
            }else {
                inventoryNum=0;
            }
            bean.setInventoryNum(inventoryNum);
        }
        return list;
    }

    /***
     * 根据ID集合查询购物车列表
     * @param ids
     * @return
     */

    @Override
    public List<ShopCart> list(List<String> ids) {
        return cartMapper.findAllById(ids);
    }

    /***
     * 根据ID删除
     * @param ids
     */
    @Override
    public R delete(List<String> ids) {
        DeleteResult i = mongoTemplate.remove(Query.query(Criteria.where("_id").in(ids)), ShopCart.class);
        if (i.getDeletedCount()<1){
            return R.fail();
        }
        return R.ok();
    }

    /***
     * Sku转Cart
     * @param sku
     * @param cart
     */
    public void sku2cart(@NotNull ShopGoodsSku sku, @NotNull ShopCart cart){
        ShopGoodsInfo goodInfo = infoService.getById(sku.getShopGoodsId());
        cart.setImage(goodInfo.getImage());
        cart.set_id(cart.getUserId().toString()+cart.getSkuId().toString());
        cart.setGoodsId(goodInfo.getId());
        cart.setName(goodInfo.getGoodsName());
        cart.setSkuName(sku.getSkuName().replaceAll(goodInfo.getGoodsName(),""));
        cart.setPrice(sku.getPrice().toString());
        cart.setOriginalPrice(sku.getOriginalPrice().toString());
        cart.setSkuId(sku.getId());
        cart.setShopId(sku.getShopId());
        H2ShopBase h2ShopBase=h2ShopBaseDao.getById(sku.getShopId());
        if (null != h2ShopBase){
            cart.setShopName(h2ShopBase.getShopName());
            cart.setShopAvatarUrl(h2ShopBase.getShopAvatarUrl());
            cart.setShopCoverUrl(h2ShopBase.getShopCoverUrl());
        }
    }

}
